//
// Created by jan on 12/1/20.
//

#include <iostream>
#include "OpusDecoder.h"

namespace yd {
    namespace audioprocess {

        OpusDecoder::OpusDecoder() {
            m_decoder = nullptr;
            int err = 0;
            m_decoder = opus_decoder_create(16000, 1, &err);
            if (err) {
                m_decoder = nullptr;
                std::cerr << "init opus decoder failed:" << err << std::endl;
                throw err;
            }
        }

        OpusDecoder::~OpusDecoder() {
            if (m_decoder) {
                opus_decoder_destroy(m_decoder);
            }
        }

        void OpusDecoder::Decode(const std::string &data, std::string *pcm) {
            pcm->resize(4096);
            auto opusBuf = (const unsigned char *) data.data();
            auto samples = opus_decode(m_decoder, opusBuf, data.size(),
                                       (opus_int16 *) (&pcm[0][0]),
                                       4096 / 2, 0);
            if (samples < 0) {
                std::cerr << "decode failed:" << samples << std::endl;
                samples = 0;
            }
            pcm->resize(samples * 2);
        }

    }
}